package com.javabase.y2022.m05.day0516.v02;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2022/5/16 上午 11:34
 * @version: 1.0
 */
public class Solution {
    // 使用鏈表實現堆棧和隊列
    public static class Node {
        int val;
        Node last;
        Node next;

        public Node(int val) {
            this.val = val;
        }
    }

    public static class MyStack1 {
        public Node top;
        public Node tail;

        public Node addFromTop(Node ele) {
            if (this.top == null) {
                top = ele;
                tail = ele;
            } else {
                top.last = ele;
                ele.next = top;
                top = ele;
            }
            return top;
        }

        public Node addFromTail(Node ele) {
            if (tail == null) {
                top = ele;
                tail = ele;
            } else {
                tail.next = ele;
                ele.last = tail;
                tail = ele;
            }
            return tail;
        }

        public Node removeFromTop() {
            Node ans;
            ans = top;
            if (top == null) {
                throw new RuntimeException("MyStack1 is empty!!");
            } else {
                Node next = top.next;
                if (next != null) {
                    top.next = null;
                    next.last = null;
                    top = next;
                } else {
                    top = null;
                    tail = null;
                }
            }
            return ans;
        }

        public Node removeFromTail() {
            Node ans = tail;
            if (tail == null) {
                throw new RuntimeException("Mystack1 is empty!!");
            }
            Node last = tail.last;
            if (last != null) {
                tail.last = null;
                last.next = null;
                tail = last;
            } else {
                tail = null;
                top = null;
            }
            return ans;
        }

        public Node pop() {
            return this.removeFromTop();
        }

        public Node peek() {
            return this.top;
        }
        public void push(Node ele){
            this.addFromTop(ele);
        }
    }
    public static class MyQueue1{

    }
}
